package org.zhouhe.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class EnumDateFormater extends SimpleDateFormat{
	private String pattern;
	private SimpleDateFormat sdf;
	public EnumDateFormater(){
	}
	public EnumDateFormater(String pattern){
		this.pattern = pattern;
		this.sdf = new SimpleDateFormat(this.pattern);
	}
	private static final long serialVersionUID = 1L;

	private static Map<String, SimpleDateFormat> dateFormaterMap = new HashMap<String, SimpleDateFormat>();
	static {
		dateFormaterMap.put("\\d+-\\d+-\\d+", new SimpleDateFormat("yyyy-MM-dd"));
		dateFormaterMap.put("\\d+-\\d+-\\d+\\s+\\d+:\\d+:\\d+", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		dateFormaterMap.put("\\d+/\\d+/\\d+", new SimpleDateFormat("yyyy/MM/dd"));
	}

	/**
	 * 将常见日期字符串转化为日期类型
	 * @param source 日期字符串，格式为常见日期格式，如: yyyy-MM-dd；yyyy-MM-dd HH:mm:ss；yyyy/MM/dd
	 */
	public Date parse(String source) {
		Date returnDate = null;
		try {
			if (source != null) {
				for (String pattern : dateFormaterMap.keySet()) {
					if (source.matches(pattern)) {
						returnDate = dateFormaterMap.get(pattern).parse(source);
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnDate;
	}

	/**
	 * 系统不会调用这个方法
	 * @param date
	 * @return
	 */
	public String formatDate(Date date){
		if(date == null){
			return null;
		}
		return sdf.format(date);
	}
}